package com.weipai.education.config.interceptor;

import com.alibaba.fastjson.JSON;
import com.weipai.education.dao.UserDao;
import com.weipai.education.enums.RetCode;
import com.weipai.education.enums.SourceStatus;
import com.weipai.education.model.User;
import com.weipai.education.model.api.Response;
import com.weipai.education.service.RoleService;
import com.weipai.education.service.UserService;
import com.weipai.education.shiro.AppCacheDao;
import com.weipai.education.utils.PasswordHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * 登录检查
 */
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LoginHandlerInterceptor.class);

    public static final String AUTH_TOKEN_HEADER = "Authentication-Token";
    
    @Autowired
    private RoleService roleService;
    @Autowired
    private AppCacheDao appCacheDao;
    @Autowired
    private UserDao userDao;
    
    
    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse resp, Object handler) throws Exception {

        Response response = new Response();
        String authToken = request.getHeader(AUTH_TOKEN_HEADER);
        
        if(authToken != null){
            //app端
            boolean isValid = false;
            try {
                isValid = PasswordHelper.validateToken(authToken);
            } catch (Exception e) {
                logger.error("validate token with error = {}", e);
            }
            if (isValid) {
                //已登录
                User user = appCacheDao.getUser(authToken);
                if (user == null) {
                    String mobile = PasswordHelper.getUserName(authToken);
                    user = userDao.getUserByMobile(mobile);
                    if (user == null) {
                        //返回未登录
                        response.setCode(RetCode.NOT_LOGIN);
                        resp.setCharacterEncoding("UTF-8");
                        resp.getWriter().append(JSON.toJSONString(response));
                        return false;
                    } else {
                        appCacheDao.save(authToken, user);
                    }
                }
                return true;
            } else {
                //返回未登录
                response.setCode(RetCode.NOT_LOGIN);
                resp.setCharacterEncoding("UTF-8");
                resp.getWriter().append(JSON.toJSONString(response));
                return false;
            }
        }else{
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            User user = (User) session.getAttribute("loginUser");
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json; charset=utf-8");
            if (user == null) {
                response.setCode(RetCode.NOT_LOGIN);
                resp.getWriter().append(JSON.toJSONString(response));
                return false;
            } else {
                Integer roleId = user.getRoleId();
                Integer type = getUserType();
                if(type != SourceStatus.MOVE.getType()){
                    //验证此roleId与menuId是否有关联
                    Integer num = roleService.verifyRoleIdAndMenuId(roleId, type);
                }
                return true;
            }
        }
    }

    public int getUserType() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String typeStr = null;
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            if(key.equals("user_type")){
                typeStr = request.getHeader(key);
            }
        }
        int type = SourceStatus.MOVE.getType();
        try {
            type = Integer.valueOf(typeStr);
        } catch (NumberFormatException e) {
            logger.warn("default user type is customer");
        }
        return type;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
    
    
}
